﻿namespace Hidistro.SqlDal.Sales
{
    using Hidistro.Entities;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Microsoft.Practices.EnterpriseLibrary.Data;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;

    public class ShoppingCartDao
    {
        private Database database = DatabaseFactory.CreateDatabase();

        public bool AddGiftItem(int giftId, int quantity, PromoteType promotype)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("IF  EXISTS(SELECT GiftId FROM Hishop_GiftShoppingCarts WHERE UserId = @UserId AND GiftId = @GiftId AND PromoType=@PromoType) UPDATE Hishop_GiftShoppingCarts SET Quantity = Quantity + @Quantity WHERE UserId = @UserId AND GiftId = @GiftId AND PromoType=@PromoType; ELSE INSERT INTO Hishop_GiftShoppingCarts(UserId, GiftId, Quantity, AddTime,PromoType) VALUES (@UserId, @GiftId, @Quantity, @AddTime,@PromoType)");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, HiContext.Current.User.UserId);
            this.database.AddInParameter(sqlStringCommand, "GiftId", DbType.Int32, giftId);
            this.database.AddInParameter(sqlStringCommand, "Quantity", DbType.Int32, quantity);
            this.database.AddInParameter(sqlStringCommand, "AddTime", DbType.DateTime, DateTime.Now);
            this.database.AddInParameter(sqlStringCommand, "PromoType", DbType.Int32, (int)promotype);
            return (this.database.ExecuteNonQuery(sqlStringCommand) > 0);
        }

        public AddCartItemStatus AddLineItem(Member member, string skuId, int quantity)
        {
            DbCommand storedProcCommand = this.database.GetStoredProcCommand("ss_ShoppingCart_AddLineItem");
            this.database.AddInParameter(storedProcCommand, "UserId", DbType.Int32, member.UserId);
            this.database.AddInParameter(storedProcCommand, "SkuId", DbType.String, skuId);
            this.database.AddInParameter(storedProcCommand, "Quantity", DbType.Int32, quantity);
            this.database.ExecuteNonQuery(storedProcCommand);
            return AddCartItemStatus.Successed;
        }

        public void ClearShoppingCart(int userId)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("DELETE FROM Hishop_ShoppingCarts WHERE UserId = @UserId; DELETE FROM Hishop_GiftShoppingCarts WHERE UserId = @UserId");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, userId);
            this.database.ExecuteNonQuery(sqlStringCommand);
        }

        public ShoppingCartItemInfo GetCartItemInfo(Member member, string skuId, int quantity)
        {
            ShoppingCartItemInfo info = null;
            DbCommand storedProcCommand = this.database.GetStoredProcCommand("ss_ShoppingCart_GetItemInfo");
            this.database.AddInParameter(storedProcCommand, "Quantity", DbType.Int32, quantity);
            this.database.AddInParameter(storedProcCommand, "UserId", DbType.Int32, (member != null) ? member.UserId : 0);
            this.database.AddInParameter(storedProcCommand, "SkuId", DbType.String, skuId);
            this.database.AddInParameter(storedProcCommand, "GradeId", DbType.Int32, (member != null) ? member.GradeId : 0);
            using (IDataReader reader = this.database.ExecuteReader(storedProcCommand))
            {
                if (reader.Read())
                {
                    info = new ShoppingCartItemInfo();
                    info.SkuId = skuId;
                    info.Quantity = info.ShippQuantity = quantity;
                    info.ProductId = (int)reader["ProductId"];
                    if (reader["SKU"] != DBNull.Value)
                    {
                        info.SKU = (string)reader["SKU"];
                    }
                    info.Name = (string)reader["ProductName"];
                    if (DBNull.Value != reader["Weight"])
                    {
                        info.Weight = (decimal)reader["Weight"];
                    }
                    info.MemberPrice = info.AdjustedPrice = (decimal)reader["SalePrice"];
                    if (DBNull.Value != reader["ThumbnailUrl40"])
                    {
                        info.ThumbnailUrl40 = reader["ThumbnailUrl40"].ToString();
                    }
                    if (DBNull.Value != reader["ThumbnailUrl60"])
                    {
                        info.ThumbnailUrl60 = reader["ThumbnailUrl60"].ToString();
                    }
                    if (DBNull.Value != reader["ThumbnailUrl100"])
                    {
                        info.ThumbnailUrl100 = reader["ThumbnailUrl100"].ToString();
                    }
                    if (DBNull.Value != reader["IsfreeShipping"])
                    {
                        info.IsfreeShipping = Convert.ToBoolean(reader["IsfreeShipping"]);
                    }
                    if (DBNull.Value != reader["CategoryUrl"])
                    {
                        info.CategoryUrl = reader["CategoryUrl"].ToString();
                    }
                    string str = string.Empty;
                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            if (!((((reader["AttributeName"] == DBNull.Value) || string.IsNullOrEmpty((string)reader["AttributeName"])) || (reader["ValueStr"] == DBNull.Value)) || string.IsNullOrEmpty((string)reader["ValueStr"])))
                            {
                                object obj2 = str;
                                str = string.Concat(new object[] { obj2, reader["AttributeName"], "：", reader["ValueStr"], "; " });
                            }
                        }
                    }
                    info.SkuContent = str;
                    PromotionInfo info2 = null;
                    if (reader.NextResult() && reader.Read())
                    {
                        info2 = DataMapper.PopulatePromote(reader);
                    }
                    if (info2 != null)
                    {
                        info.PromoteType = info2.PromoteType;
                        switch (info2.PromoteType)
                        {
                            case PromoteType.Discount:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info.MemberPrice * info2.DiscountValue;
                                return info;

                            case PromoteType.Amount:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info2.DiscountValue;
                                return info;

                            case PromoteType.Reduced:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info.MemberPrice - info2.DiscountValue;
                                return info;

                            case PromoteType.QuantityDiscount:
                                if (info.Quantity >= ((int)info2.Condition))
                                {
                                    info.PromotionId = info2.ActivityId;
                                    info.PromotionName = info2.Name;
                                    info.AdjustedPrice = info.MemberPrice * info2.DiscountValue;
                                }
                                return info;

                            case PromoteType.SentGift:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.IsSendGift = true;
                                return info;

                            case PromoteType.SentProduct:
                                if ((info.Quantity / ((int)info2.Condition)) >= 1)
                                {
                                    info.PromotionId = info2.ActivityId;
                                    info.PromotionName = info2.Name;
                                    info.ShippQuantity = info.Quantity + ((info.Quantity / ((int)info2.Condition)) * ((int)info2.DiscountValue));
                                }
                                return info;
                        }
                    }
                }
                return info;
            }
        }
        public ShoppingCartItemInfo GetCartItemInfo_danping(Member member, string skuId, int quantity)
        {
            ShoppingCartItemInfo info = null;
            DbCommand storedProcCommand = this.database.GetStoredProcCommand("ss_ShoppingCart_GetItemInfo_danping");
            this.database.AddInParameter(storedProcCommand, "Quantity", DbType.Int32, quantity);
            this.database.AddInParameter(storedProcCommand, "UserId", DbType.Int32, (member != null) ? member.UserId : 0);
            this.database.AddInParameter(storedProcCommand, "SkuId", DbType.String, skuId);
            this.database.AddInParameter(storedProcCommand, "GradeId", DbType.Int32, (member != null) ? member.GradeId : 0);
            using (IDataReader reader = this.database.ExecuteReader(storedProcCommand))
            {
                if (reader.Read())
                {
                    info = new ShoppingCartItemInfo();
                    info.SkuId = skuId;
                    info.Quantity = info.ShippQuantity = quantity;
                    info.ProductId = (int)reader["ProductId"];
                    if (reader["SKU"] != DBNull.Value)
                    {
                        info.SKU = (string)reader["SKU"];
                    }
                    info.Name = (string)reader["ProductName"];
                    if (DBNull.Value != reader["Weight"])
                    {
                        info.Weight = (decimal)reader["Weight"];
                    }
                    info.MemberPrice = info.AdjustedPrice = (decimal)reader["SalePrice"];
                    if (DBNull.Value != reader["ThumbnailUrl40"])
                    {
                        info.ThumbnailUrl40 = reader["ThumbnailUrl40"].ToString();
                    }
                    if (DBNull.Value != reader["ThumbnailUrl60"])
                    {
                        info.ThumbnailUrl60 = reader["ThumbnailUrl60"].ToString();
                    }
                    if (DBNull.Value != reader["ThumbnailUrl100"])
                    {
                        info.ThumbnailUrl100 = reader["ThumbnailUrl100"].ToString();
                    }
                    if (DBNull.Value != reader["IsfreeShipping"])
                    {
                        info.IsfreeShipping = Convert.ToBoolean(reader["IsfreeShipping"]);
                    }
                    if (DBNull.Value != reader["CategoryUrl"])
                    {
                        info.CategoryUrl = reader["CategoryUrl"].ToString();
                    }
                    string str = string.Empty;
                    if (reader.NextResult())
                    {
                        while (reader.Read())
                        {
                            if (!((((reader["AttributeName"] == DBNull.Value) || string.IsNullOrEmpty((string)reader["AttributeName"])) || (reader["ValueStr"] == DBNull.Value)) || string.IsNullOrEmpty((string)reader["ValueStr"])))
                            {
                                object obj2 = str;
                                str = string.Concat(new object[] { obj2, reader["AttributeName"], "：", reader["ValueStr"], "; " });
                            }
                        }
                    }
                    info.SkuContent = str;
                    PromotionInfo info2 = null;
                    if (reader.NextResult() && reader.Read())
                    {
                        info2 = DataMapper.PopulatePromote(reader);
                    }
                    if (info2 != null)
                    {
                        info.PromoteType = info2.PromoteType;
                        switch (info2.PromoteType)
                        {
                            case PromoteType.Discount:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info.MemberPrice * info2.DiscountValue;
                                return info;

                            case PromoteType.Amount:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info2.DiscountValue;
                                return info;

                            case PromoteType.Reduced:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.AdjustedPrice = info.MemberPrice - info2.DiscountValue;
                                return info;

                            case PromoteType.QuantityDiscount:
                                if (info.Quantity >= ((int)info2.Condition))
                                {
                                    info.PromotionId = info2.ActivityId;
                                    info.PromotionName = info2.Name;
                                    info.AdjustedPrice = info.MemberPrice * info2.DiscountValue;
                                }
                                return info;

                            case PromoteType.SentGift:
                                info.PromotionId = info2.ActivityId;
                                info.PromotionName = info2.Name;
                                info.IsSendGift = true;
                                return info;

                            case PromoteType.SentProduct:
                                if ((info.Quantity / ((int)info2.Condition)) >= 1)
                                {
                                    info.PromotionId = info2.ActivityId;
                                    info.PromotionName = info2.Name;
                                    info.ShippQuantity = info.Quantity + ((info.Quantity / ((int)info2.Condition)) * ((int)info2.DiscountValue));
                                }
                                return info;
                        }
                    }
                }
                return info;
            }
        }

        public int GetGiftItemQuantity(PromoteType promotype)
        {
            int num = 0;
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("SELECT ISNULL(SUM(Quantity),0) as Quantity FROM Hishop_GiftShoppingCarts WHERE UserId = @UserId AND PromoType=@PromoType");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, HiContext.Current.User.UserId);
            this.database.AddInParameter(sqlStringCommand, "PromoType", DbType.Int32, (int)promotype);
            using (IDataReader reader = this.database.ExecuteReader(sqlStringCommand))
            {
                if (reader.Read())
                {
                    num = int.Parse(reader["Quantity"].ToString());
                }
            }
            return num;
        }

        public ShoppingCartInfo GetShoppingCart(int userId, IList<string> NotSelect = null)
        {
            ShoppingCartInfo info = new ShoppingCartInfo();
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("SELECT * FROM Hishop_ShoppingCarts WHERE UserId = @UserId;SELECT * FROM Hishop_GiftShoppingCarts gc JOIN Hishop_Gifts g ON gc.GiftId = g.GiftId WHERE gc.UserId = @UserId");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, userId);
            using (IDataReader reader = this.database.ExecuteReader(sqlStringCommand))
            {
                Member user = HiContext.Current.User as Member;
                while (reader.Read())
                {
                    ShoppingCartItemInfo item = this.GetCartItemInfo(user, (string)reader["SkuId"], (int)reader["Quantity"]);
                    if (item != null)
                    {
                        if (NotSelect != null && NotSelect.Count > 0)
                        {
                            if (NotSelect.Contains((string)reader["SkuId"])) item.IsSelect = false;
                        }
                        info.LineItems.Add(item);
                    }
                }
                reader.NextResult();
                while (reader.Read())
                {
                    ShoppingCartGiftInfo info3 = DataMapper.PopulateGiftCartItem(reader);
                    info3.Quantity = (int)reader["Quantity"];
                    info.LineGifts.Add(info3);
                }
            }
            return info;
        }

        public void RemoveGiftItem(int giftId, PromoteType promotype)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("DELETE FROM Hishop_GiftShoppingCarts WHERE UserId = @UserId AND GiftId = @GiftId AND PromoType=@PromoType");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, HiContext.Current.User.UserId);
            this.database.AddInParameter(sqlStringCommand, "GiftId", DbType.Int32, giftId);
            this.database.AddInParameter(sqlStringCommand, "PromoType", DbType.Int32, (int)promotype);
            this.database.ExecuteNonQuery(sqlStringCommand);
        }

        public void RemoveLineItem(int userId, string skuId)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("DELETE FROM Hishop_ShoppingCarts WHERE UserId = @UserId AND SkuId = @SkuId");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, userId);
            this.database.AddInParameter(sqlStringCommand, "SkuId", DbType.String, skuId);
            this.database.ExecuteNonQuery(sqlStringCommand);
        }

        public void UpdateGiftItemQuantity(int giftId, int quantity, PromoteType promotype)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("UPDATE Hishop_GiftShoppingCarts SET Quantity = @Quantity WHERE UserId = @UserId AND GiftId = @GiftId AND PromoType=@PromoType");
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, HiContext.Current.User.UserId);
            this.database.AddInParameter(sqlStringCommand, "GiftId", DbType.Int32, giftId);
            this.database.AddInParameter(sqlStringCommand, "Quantity", DbType.Int32, quantity);
            this.database.AddInParameter(sqlStringCommand, "PromoType", DbType.Int32, (int)promotype);
            this.database.ExecuteNonQuery(sqlStringCommand);
        }

        public void UpdateLineItemQuantity(Member member, string skuId, int quantity)
        {
            DbCommand sqlStringCommand = this.database.GetSqlStringCommand("UPDATE Hishop_ShoppingCarts SET Quantity = @Quantity WHERE UserId = @UserId AND SkuId = @SkuId");
            this.database.AddInParameter(sqlStringCommand, "Quantity", DbType.Int32, quantity);
            this.database.AddInParameter(sqlStringCommand, "UserId", DbType.Int32, member.UserId);
            this.database.AddInParameter(sqlStringCommand, "SkuId", DbType.String, skuId);
            this.database.ExecuteNonQuery(sqlStringCommand);
        }
    }
}

